<?php
/**
 * Created by PhpStorm.
 * User: zd
 * Date: 2018/8/14
 * Time: 15:45
 */

namespace app\api\model;



class User extends BaseModel
{
    protected $hidden=['delete_time','create_time','update_time'];
    protected $autoWriteTimestamp = true;
    /**
     * 与user_address表一对一关联
     * @return \think\model\relation\HasOne
     */
    public function address(){
        return $this->hasOne('UserAddress','user_id','id');
    }
    /**
     * 与work_user表多对多关联
     * @return \think\model\relation\BelongsToMany
     */
    public function workuser(){
        return $this->belongsToMany('WorkUser','user_workuser','wu_id','user_id');
    }

    /**
     * 与label表多对多关系
     * @return \think\model\relation\BelongsToMany
     */
    public function labels(){
        return $this->belongsToMany('Label','user_label','label_id','user_id');
    }

    /**
     * 与user_label一对多关系
     * @return \think\model\relation\HasMany
     */
    public function userlabels(){
        return $this->hasMany('UserLabel','user_id','id');
    }

    /**
     * 与behavior表为一对多关系
     * @return \think\model\relation\HasMany
     */
    public function behavior(){
        return $this->hasMany('Behavior','user_id','id');
    }
    /**
     * 根据openID获取用户信息
     * @param $openid
     * @return array|false|\PDOStatement|string|\think\Model
     */
    public static function getUserInfoByOpenID($openid){
        return self::where('openid','=',$openid)->find();
    }

    /**
     * 获取用户信息
     * @param $id
     * @return null|static
     */
    public static function getUserInfoByUid($id){
        return self::get($id);
    }

    /**
     * 根据openID创建用户
     * @param $openid
     * @return mixed
     */
    public static function createUserByOpenId($t_id,$openid,$session_key)
    {
        $user = self::create([
            't_id'=>$t_id,
            'openid'=>$openid,
            'session_key'=>$session_key,
        ]);
        return $user->id;
    }

    /**
     * 创建关系
     * @param $uid 用户id
     * @param $wu_id 名片id
     * @param $source(来源)
     * @param $sharer(分享人id)
     * @return int
     * @throws \think\exception\DbException
     */
    public function createFather($uid,$wu_id,$source,$sharer){
        //添加关系到用户名片中间表
        $user = self::get($uid);
        $work_user = WorkUser::get($wu_id);
        $result = $user->workUser()->save($work_user,[ 'source'=>$source,'third_leader'=>$sharer,'create_time'=>time()]);
        return $result;
    }
    /**
     * 更新用户数据
     * @param $uid
     * @param $unionid
     * @param $data
     * @return $this
     */
    public function updateUserInfo($uid,$t_id,$data){
        //更新用户其他信息
        $user['t_id'] = $t_id;
        $user['nickname'] = $data['nickName'];
        $user['gender'] = $data['gender'];
        $user['city'] = $data['city'];
        $user['province'] = $data['province'];
        $user['avatar_url'] = $data['avatarUrl'];
        return  self::update($user,['id'=>$uid]);
    }
    /**
     * 查询用户是否授权电话
     * @param $user_id
     * @return array|false|\PDOStatement|string|\think\Model
     */
    public static function checkAuthPhone($user_id){
        $result = self::where('id','=',$user_id)->field('authorize_phone')->find();
        return $result;
    }

    /**
     * 推荐名片列表
     * @param $manager_id
     * @param $data
     * @return mixed
     */
    public function recommendCardList($manager_id, $data)
    {
        $workusers = WorkUser::with(['card', 'userimg', 'thirdapp'])
            ->where('t_id', '=', $manager_id)
            ->where('recommond', '=', '1')
            ->select();
        foreach ($workusers as $workuser) {
            $workuser->visible(['id', 'name', 'position', 'card', 'thirdapp', 'userimg']);
            $workuser->thirdapp->visible(['head_img', 'name', 'sub_name']);
            if ($workuser->userimg != null) {
                $workuser->userimg->visible(['url']);
            }
        }
        $workusers = $workusers->toArray();
        $data['workuser'] = $workusers;
        $data['type'] = 'first';
        return $data;
    }
    /**
     * 用户已有名片列表
     * @param $uid
     * @return $this
     */
    public function ownCardList($uid){
        //获取已有名片列表
        $userInfo = User::with(['workuser' => ['card', 'userimg', 'thirdapp']])->find($uid)->visible(['id', 'workuser']);
        $workusers = $userInfo->workuser->visible(['id', 'name', 'position', 'card', 'pivot', 'thirdapp', 'userimg']);
        foreach ($workusers as $workuser) {
            $workuser->pivot->visible(['source', 'shield', 'create_time']);
            $workuser->thirdapp->visible(['head_img', 'name', 'sub_name']);
            if (!is_array($workuser->userimg)) {
                $workuser->userimg->visible(['url']);
           }
        }
        $userInfo =  $userInfo->toArray();
        $userInfo['type'] = 'second';
        return $userInfo;
    }
    /**
     * 获取名片详情
     * @param $uid
     * @param $wu_id
     * @return array|false|\PDOStatement|string|\think\Model
     */
    public static function getCardInfo($wu_id){
        $card = new WorkUser();
        $cardInfo = $card::getUserInfo($wu_id);
        return $cardInfo;
    }

    /**
     * 获取名片拓展信息
     * @param $wu_id
     * @return $this
     */
    public static function getCardExtendInfo($wu_id){
        $card = new WorkUser();
        $cardInfo = $card::getExtendInfo($wu_id);
        return $cardInfo;
    }

    /**
     * 更新用户授权电话
     * @param $phone
     * @param $uid
     * @return $this
     */
    public static function updatePhone($phone,$uid){
        $data['authorize_phone'] = $phone;
        return self::where('id','=',$uid)->update($data);
    }


    /**
     * 添加用户标签
     * @param $uid
     * @param $data
     * @return int
     */
    public static function addUserLabel($wu_id,$data){
            $user =  self::get($data['user_id']);
            $info = '';
            foreach ($data['label'] as $key=>$value){
                    $info[$key]['wu_id'] = $wu_id;
                    $info[$key]['name'] = $value;
            }
            return $user->labels()->saveAll($info,['wu_id'=>$wu_id],true);
    }

    /**
     * 根据ID添加标签
     * @param $data
     * @param $wu_id
     * @return array|false
     */
    public static function addUserLabelById($data,$wu_id){
        foreach ($data['add'] as $key=>$value){
            $info[$key]['user_id'] = $data['user_id'];
            $info[$key]['label_id'] = $value;
            $info[$key]['wu_id'] = $wu_id;
        }
      return (new UserLabel())->saveAll($info);//新建关系
    }

    /**
     * 删除已有标签
     * @param $data
     * @return int
     */
    public static function deleteUserLabelById($data){
        $user = self::get($data['user_id']);
        return $user->labels()->detach($data['del']);
    }

    /**
     * 请求用户标签
     * @param $uid
     * @return array|false|\PDOStatement|string|\think\Model
     */
    public static function getLabelByUser($wu_id,$uid){
        $label = self::alias('a')->where('a.id','=',$uid)
           ->join('xhy_user_label u','u.user_id = a.id')
            ->join('xhy_label l','l.id = u.label_id')
            ->where('l.wu_id','=',$wu_id)
            ->field('l.id,l.name,l.sort')
            ->select();
        return $label;
    }

    /**
     *获取行为
     * @param $ids
     * @return false|\PDOStatement|string|\think\Collection
     */
    public static function getBehaviorListByIds($ids,$time){
        $result = self::withCount(['behavior'=>function($query)use($time){
            $query->partition([],'user_id',array('type' => 'mod','num' =>4))
                ->where('add_time','>',$time['start'])
                ->where('add_time','<',$time['end']);
            }])->where('id','in',$ids)
            ->select();
        foreach ($result as $value){
            $value->visible(['id','nickname','avatar_url','behavior_count']);
        }
        return $result;
    }


}